<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KPI指标管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei';
            background-color: #f5f5f5;
            overflow-x: hidden;
        }

        .container {
            min-height: 100vh;
            display: flex;
            padding: 10px;
            box-sizing: border-box;
        }

        .main-panel {
            width: 100%;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            text-align: center;
            flex-shrink: 0;
        }

        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }

        .toolbar-section {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            background-color: #ffffff;
            flex-shrink: 0;
        }

        .table-section {
            flex: 1;
            padding: 10px;
            overflow: auto;
            min-height: 0;
            margin-top: 10px;
            background-color: #ffffff;
        }

        .indicator-name {
            display: inline-block;
            gap: 4px;
        }

        .chinese-name {
            font-weight: 500;
            color: #2c3e50;
        }

        .english-name {
            font-size: 12px;
            color: #606266;
            font-style: italic;
        }

        .score-range {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            font-weight: 500;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="main-panel">
                <!-- <div class="header">
                    <h1>KPI指标管理</h1>
                    <p>管理企业KPI指标体系，支持两级指标分类和评分规则配置</p>
                </div> -->

                <div class="toolbar-section">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h3>指标管理</h3>
                        <div>
                            <el-button type="primary" size="small" icon="el-icon-plus"
                                @click="createNewIndicator">新增指标</el-button>
                        </div>
                    </div>
                </div>



                <div class="table-section">
                    <el-table :data="displayIndicators" style="width: 100%;" border row-key="id"
                        :tree-props="{children: 'children'}">
                        <el-table-column label="名称" min-width="300">
                            <template slot-scope="scope">
                                <div class="indicator-name">
                                    <div class="chinese-name"><el-tag>{{ scope.row.chineseName }}</el-tag> {{
                                        scope.row.englishName }}
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="打分区间" min-width="120" align="center">
                            <template slot-scope="scope">
                                <div class="score-range"
                                    v-if="scope.row.scoreMin !== null && scope.row.scoreMax !== null">
                                    <span>{{ scope.row.scoreMin }}</span>~<span>{{ scope.row.scoreMax }}</span>
                                </div>
                                <span v-else style="color: #909399;">-</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="打分规则" min-width="200" show-overflow-tooltip>
                            <template slot-scope="scope">{{ scope.row.scoringRules || '-' }}</template>
                        </el-table-column>
                        <el-table-column label="排序" min-width="80" align="center">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.sortOrder" :min="1" :max="999" size="mini"
                                    controls-position="right" @change="updateSortOrder(scope.row)"
                                    style="width: 80px;"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="备注" min-width="150" show-overflow-tooltip>
                            <template slot-scope="scope">{{ scope.row.remarks || '-' }}</template>
                        </el-table-column>
                        <el-table-column label="操作" min-width="160" align="center" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="editIndicator(scope.row)">编辑</el-button>
                                <el-button v-if="canAddSubIndicator(scope.row)" type="text" size="small"
                                    @click="addSubIndicator(scope.row)">添加子指标</el-button>
                                <el-button type="text" size="small" style="color: #f56c6c;"
                                    @click="deleteIndicator(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>



        <!-- 新增/编辑指标对话框 -->
        <el-dialog :title="getDialogTitle()" :visible.sync="indicatorFormDialogVisible" width="600px">
            <el-form :model="indicatorForm" label-width="120px" :rules="indicatorFormRules" ref="indicatorForm">
                <el-form-item label="所属大类" prop="parentId" v-if="showParentSelection">
                    <el-select v-model="indicatorForm.parentId" placeholder="选择所属大类" style="width: 100%;">
                        <el-option v-for="category in parentOptions" :key="category.id" :label="category.chineseName"
                            :value="category.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="中文名称" prop="chineseName">
                    <el-input v-model="indicatorForm.chineseName" placeholder="请输入中文名称"></el-input>
                </el-form-item>
                <el-form-item label="英文名称" prop="englishName">
                    <el-input v-model="indicatorForm.englishName" placeholder="请输入英文名称"></el-input>
                </el-form-item>
                <el-form-item label="打分区间">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <el-input-number v-model="indicatorForm.scoreMin" :min="0" :max="150" placeholder="最小值"
                            style="width: 150px;"></el-input-number>
                        <span>~</span>
                        <el-input-number v-model="indicatorForm.scoreMax" :min="0" :max="150" placeholder="最大值"
                            style="width: 150px;"></el-input-number>
                    </div>
                </el-form-item>
                <el-form-item label="打分规则">
                    <el-input v-model="indicatorForm.scoringRules" type="textarea" :rows="4"
                        placeholder="请输入详细的打分规则和标准"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sortOrder">
                    <el-input-number v-model="indicatorForm.sortOrder" :min="1" :max="999" controls-position="right"
                        style="width: 150px;"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="indicatorForm.remarks" type="textarea" :rows="3"
                        placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="indicatorFormDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitIndicatorForm">确定</el-button>
            </div>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="kpi-indicator-data.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    indicatorList: [],
                    displayIndicators: [],

                    indicatorFormDialogVisible: false,
                    isEditMode: false,
                    indicatorForm: { id: '', parentId: '', chineseName: '', englishName: '', scoreMin: null, scoreMax: null, scoringRules: '', sortOrder: 1, remarks: '' },
                    indicatorFormRules: {
                        parentId: [{ required: true, message: '请选择所属大类', trigger: 'change' }],
                        chineseName: [{ required: true, message: '请输入中文名称', trigger: 'blur' }],
                        englishName: [{ required: true, message: '请输入英文名称', trigger: 'blur' }],
                        sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }]
                    }
                }
            },
            computed: {
                parentOptions() {
                    return this.indicatorList.filter(item => !item.parentId);
                },
                showParentSelection() {
                    return this.isEditMode ? !!this.indicatorForm.parentId : true;
                }
            },
            mounted() {
                this.loadIndicatorList();
                this.displayIndicators = [...this.indicatorList];
            },
            methods: {
                loadIndicatorList() {
                    this.indicatorList = IndicatorDataManager.getDefaultData();
                },

                createNewIndicator() {
                    this.isEditMode = false;
                    this.indicatorForm = { id: '', parentId: '', chineseName: '', englishName: '', scoreMin: null, scoreMax: null, scoringRules: '', sortOrder: 1, remarks: '' };
                    this.indicatorFormDialogVisible = true;
                },
                addSubIndicator(parentIndicator) {
                    this.isEditMode = false;
                    this.indicatorForm = { id: '', parentId: parentIndicator.id, chineseName: '', englishName: '', scoreMin: null, scoreMax: null, scoringRules: '', sortOrder: 1, remarks: '' };
                    this.indicatorFormDialogVisible = true;
                },
                canAddSubIndicator(indicator) {
                    // 只有没有父级的指标（即顶级指标）才能添加子指标
                    return !indicator.parentId;
                },
                editIndicator(indicator) {
                    this.isEditMode = true;
                    this.indicatorForm = { ...indicator };
                    this.indicatorFormDialogVisible = true;
                },
                getDialogTitle() {
                    if (this.isEditMode) {
                        return '编辑指标';
                    }
                    return this.indicatorForm.parentId ? '新增子指标' : '新增指标';
                },
                submitIndicatorForm() {
                    this.$refs.indicatorForm.validate((valid) => {
                        if (valid) {
                            const now = new Date().toISOString();
                            if (this.isEditMode) {
                                this.indicatorForm.updateTime = now;
                                this.updateIndicatorInList(this.indicatorForm);
                                this.$message.success('指标更新成功');
                            } else {
                                const newIndicator = {
                                    ...this.indicatorForm,
                                    id: Date.now().toString() + Math.random().toString(36).substr(2, 5),
                                    level: this.indicatorForm.parentId ? 'sub' : 'major',
                                    createTime: now,
                                    updateTime: now
                                };
                                this.addIndicatorToList(newIndicator);
                                this.$message.success('指标创建成功');
                            }
                            this.displayIndicators = [...this.indicatorList];
                            this.indicatorFormDialogVisible = false;
                        }
                    });
                },
                addIndicatorToList(indicator) {
                    if (!indicator.parentId) {
                        // 顶级指标
                        this.indicatorList.push(indicator);
                    } else {
                        // 子指标
                        const parent = this.findIndicatorById(indicator.parentId);
                        if (parent) {
                            if (!parent.children) parent.children = [];
                            parent.children.push(indicator);
                        }
                    }
                },
                updateIndicatorInList(indicator) {
                    const updateInTree = (items) => {
                        for (let i = 0; i < items.length; i++) {
                            if (items[i].id === indicator.id) {
                                Object.assign(items[i], indicator);
                                return true;
                            }
                            if (items[i].children && updateInTree(items[i].children)) {
                                return true;
                            }
                        }
                        return false;
                    };
                    updateInTree(this.indicatorList);
                },
                findIndicatorById(id) {
                    const findInTree = (items) => {
                        for (const item of items) {
                            if (item.id === id) return item;
                            if (item.children) {
                                const found = findInTree(item.children);
                                if (found) return found;
                            }
                        }
                        return null;
                    };
                    return findInTree(this.indicatorList);
                },
                updateSortOrder(indicator) {
                    indicator.updateTime = new Date().toISOString();
                    this.$message.success('排序已更新');
                },
                deleteIndicator(indicator) {
                    const hasChildren = indicator.children && indicator.children.length > 0;
                    const confirmText = hasChildren ? `指标"${indicator.chineseName}"下还有${indicator.children.length}个子指标，删除后子指标也将被删除。确定要删除吗？` : `确定要删除指标"${indicator.chineseName}"吗？删除后无法恢复。`;
                    this.$confirm(confirmText, '删除指标', { confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' }).then(() => {
                        this.removeIndicatorFromList(indicator.id);
                        this.displayIndicators = [...this.indicatorList];
                        this.$message.success('指标删除成功');
                    });
                },
                removeIndicatorFromList(id) {
                    const removeFromTree = (items) => {
                        for (let i = 0; i < items.length; i++) {
                            if (items[i].id === id) {
                                items.splice(i, 1);
                                return true;
                            }
                            if (items[i].children && removeFromTree(items[i].children)) {
                                return true;
                            }
                        }
                        return false;
                    };
                    removeFromTree(this.indicatorList);
                }
            }
        });
    </script>